package com.choudou5.solr.framework.util;

import com.choudou5.solr.framework.holder.RequestContextHolder;
import com.choudou5.solr.framework.holder.SessionContextHolder;
import com.choudou5.solr.framework.job.JobFactory;
import com.choudou5.solr.framework.util.cache.EhCacheHelper;
import com.choudou5.solr.util.ConfigUtil;
import com.choudou5.solr.util.LogDeBugUtil;
import com.choudou5.solr.util.jdbc.DataSourceConfig;
import com.choudou5.solr.util.jdbc.DataSourceFactory;

/**
 * @Name：系统工具类
 * @@author choudou5
 * @@date 2018-07-16
 */
public class SysUtil {

    public static void shutdownHandler(){
        LogDeBugUtil.debug("关闭系统-------开始");
        RequestContextHolder.resetRequest();
        SessionContextHolder.removeUserSessionBean();
        EhCacheHelper.getInstance().shutdown();
        DataSourceFactory.closeDataSource();
        JobFactory.shutdown();
        LogDeBugUtil.debug("关闭系统-------结束");
    }

    public static void initHandler() throws Exception {
        LogDeBugUtil.debug("初始化系统-------开始");
        DataSourceFactory.initDataSource(buildDataSourceConfig());
        JobFactory.startup();
        LogDeBugUtil.debug("初始化系统-------结束");
    }

    public static DataSourceConfig buildDataSourceConfig(){
        DataSourceConfig config = new DataSourceConfig();
        config.setDriverClass(ConfigUtil.getStr("jdbc.driver"));
        config.setJdbcUrl(ConfigUtil.getStr("jdbc.url"));
        config.setUsername(ConfigUtil.getStr("jdbc.username"));
        config.setPassword(ConfigUtil.getStr("jdbc.password"));
        config.setInitialSize(ConfigUtil.getInt("jdbc.initialSize"));
        config.setMaxActive(ConfigUtil.getInt("jdbc.maxActive"));
        config.setMinIdle(ConfigUtil.getInt("jdbc.minIdle"));
        config.setMaxWait(ConfigUtil.getInt("jdbc.maxWait"));
        config.setRemoveAbandoned(ConfigUtil.getBool("jdbc.removeAbandoned"));
        config.setRemoveAbandonedTimeoutMillis(ConfigUtil.getInt("jdbc.removeAbandonedTimeout"));
        config.setTimeBetweenEvictionRunsMillis(ConfigUtil.getLong("jdbc.timeBetweenEvictionRunsMillis"));
        config.setMinEvictableIdleTimeMillis(ConfigUtil.getLong("jdbc.minEvictableIdleTimeMillis"));
        config.setValidationQuery(ConfigUtil.getStr("jdbc.validationQuery"));
        config.setTestWhileIdle(ConfigUtil.getBool("jdbc.testWhileIdle"));
        config.setTestOnBorrow(ConfigUtil.getBool("jdbc.testOnBorrow"));
        config.setTestOnReturn(ConfigUtil.getBool("jdbc.testOnReturn"));
        config.setPoolPreparedStatements(ConfigUtil.getBool("jdbc.poolPreparedStatements"));
        config.setMaxPoolPreparedStatementPerConnectionSize(ConfigUtil.getInt("jdbc.maxPoolPreparedStatementPerConnectionSize"));
        config.setFilters(ConfigUtil.getStr("jdbc.filters"));
        return config;
    }
}
